import React, { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { Form, Button, Input, Image, Divider, message } from "antd";
import {
  UserOutlined,
  LockOutlined,
  SafetyCertificateOutlined,
} from "@ant-design/icons";
import { setToken } from "@/stores/actions";
import { $get, $post } from "@/api/RestUtils";
import { v4 as uuidv4 } from "uuid";
import { encrypt } from "@/utils/RSAUtils";
import { useDispatch } from "react-redux";
import "./index.less";

const App: React.FC = () => {
  const [loginForm] = Form.useForm();

  const [validateCodeImg, setValidateCodeImg] = useState();

  const navigate = useNavigate();
  const dispatch = useDispatch();

  let sign = localStorage.getItem("sign");

  let firstLoaded = false;

  useEffect(() => {
    if (!sign || sign.length === 0) {
      let uuid = uuidv4();
      sign = uuid;
      localStorage.setItem("sign", uuid);
    }
    if (!firstLoaded) {
      getValidateCodeImg();
      firstLoaded = true;
    }
  }, []);

  const getValidateCodeImg = () => {
    let param = {
      sign: localStorage.getItem("sign"),
    };
    $get("/user/getValidateCodeImg", param)
      .then((res: any) => {
        if (res.code === 0) {
          setValidateCodeImg(res.data);
        } else {
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  const login = (formData: any) => {
    formData.password = encrypt(formData.password);
    let param = {
      sign: localStorage.getItem("sign"),
      ...formData,
    };
    $post("/user/login", param)
      .then((res: any) => {
        if (res.code === 0) {
          dispatch(setToken(res.data))
          message.success(res.msg);
          navigate("/index");
        } else {
          getValidateCodeImg();
          message.error(res.msg);
        }
      })
      .catch((err: any) => {
        message.error("系统异常");
      });
  };

  return (
    <div className="page-body">
      <div className="login-info">
        <div className="title">Whale Admin</div>
        <Divider />
        <div className="form-body">
          <Form
            form={loginForm}
            labelAlign="right"
            colon={false}
            onFinish={login}
          >
            <Form.Item
              name="username"
              rules={[
                {
                  required: true,
                  type: "string",
                  message: "",
                },
              ]}
              required
            >
              <Input
                prefix={<UserOutlined style={{ color: "gray" }} />}
                maxLength={12}
                placeholder="账号"
              />
            </Form.Item>
            <Form.Item
              name="password"
              rules={[
                {
                  required: true,
                  type: "string",
                  min: 8,
                  max: 16,
                  message: "",
                },
              ]}
              required
            >
              <Input
                prefix={<LockOutlined style={{ color: "gray" }} />}
                maxLength={16}
                placeholder="密码"
                type="password"
              />
            </Form.Item>
            <div className="form-validate-item">
              <Form.Item
                name="validateCode"
                rules={[
                  {
                    required: true,
                    type: "string",
                    min: 4,
                    max: 4,
                    message: "",
                  },
                ]}
                required
              >
                <Input
                  prefix={
                    <SafetyCertificateOutlined style={{ color: "gray" }} />
                  }
                  maxLength={4}
                  placeholder="验证码"
                />
              </Form.Item>
              <Image
                src={validateCodeImg}
                preview={false}
                onClick={() => getValidateCodeImg()}
              />
            </div>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>
    </div>
  );
};

export default App;
